import json
import logging
import os
import urllib
import webapp2

from google.appengine.ext        import webapp, blobstore
from google.appengine.ext.webapp import template, blobstore_handlers



class SelectFileForm(webapp.RequestHandler):
    def get(self):
        logging.debug("Select file form requested")
        file_upload_url = blobstore.create_upload_url(webapp2.uri_for("file_upload"))
        template_path   = os.path.join(os.path.dirname(__file__), "../templates/file-upload-form.html")
        self.response.out.write(template.render(template_path, { "file_upload_url": file_upload_url }))


class FileUpload(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        # Getting BlobInfo entity via key, because BlobInfo returned by
        # get_uploads() have shortened/wrong filenames.
        uploaded_key = self.get_uploads("file")[0].key()
        uploaded_blob_info = blobstore.BlobInfo.get(uploaded_key)
        filename = uploaded_blob_info.filename
        logging.info("Uploaded file %s with blob key %s" %
            (filename, str(uploaded_blob_info.key())))
        
        self.response.out.write(json.dumps({
            "filename": filename,
            "key"     : str(uploaded_blob_info.key())
        }))


class FileDownload(blobstore_handlers.BlobstoreDownloadHandler):
    def get(self, blob_key):
        blob_info = blobstore.BlobInfo.get(urllib.unquote(blob_key))
        if blob_info:
            logging.debug("Downloading file %s with blob key %s" %
                (blob_info.filename, str(blob_info.key())))
            self.send_blob(blob_info, save_as = True)
        else:
            logging.error("Invalid file download request: no blob with key %s" %
                blob_key)
            self.response.out.write("Invalid link")